import 'package:cbec_app/components/base/base_customize_segmented_control.dart';
import 'package:cbec_app/components/base/base_image.dart';
import 'package:cbec_app/components/base/base_interactive.dart';
import 'package:cbec_app/components/common/common_style.dart';
import 'package:cbec_app/components/common/count_down_timer.dart';
import 'package:cbec_app/components/common/not_found.dart';
import 'package:cbec_app/pages/goods/controller/pre_sales_ctr.dart';
import 'package:cbec_app/pages/goods/entity/activity_item_entity.dart';
import 'package:cbec_app/routes/routes.dart';
import 'package:cbec_app/utils/Tools.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../binding/goods_detail_binding.dart';
import 'goods_detail_page.dart';

//预售
class PreSales extends GetView<PreSalesController> {
  const PreSales({super.key});

  List<Widget> _createItemWidgets() {
    final PreSalesController controller = Get.find<PreSalesController>();
    List<Widget> widgetArr = [];
    for (int i = 0; i < controller.itemList.length; i++) {
      ActivityItemEntity item = controller.itemList[i];
      int selectIndex = controller.selected;
      if (i == 0) {
        widgetArr.add(
          Container(
            padding: const EdgeInsets.only(left: 5, top: 5, bottom: 0, right: 5),
            child: Column(
              // mainAxisAlignment: MainAxisAlignment.center,
              children: [
                CountDownTimer(
                  timeStamp: DateTime.parse(item.endtime ?? '').millisecondsSinceEpoch,
                  timeStyle: TimeStyle.hhmmss,
                  countDownStyle: CountDownStyle.box,
                  boxBackgroundColor: Tools.fromHex("#000000"),
                  colonColor: Tools.fromHex("#000000"),
                  style: setTextStyle(
                    12,
                    FontWeight.w400,
                    Tools.fromHex('#FFFFFF'),
                  ),
                  callback: () {},
                ),
                const SizedBox(
                  height: 5,
                ),
                Text(
                  '正在抢购',
                  style: TextStyle(
                    color: selectIndex == i ? Tools.fromHex('#F83F2D') : Tools.fromHex('#FFFFFF'),
                  ),
                ),
              ],
            ),
          ),
        );
      } else {
        widgetArr.add(
          Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                item.begintime ?? '',
                style: TextStyle(
                  color: selectIndex == i ? Tools.fromHex('#F83F2D') : Tools.fromHex('#FFFFFF'),
                ),
              ),
              const SizedBox(
                height: 3,
              ),
              Text(
                '即将开始',
                style: TextStyle(color: selectIndex == i ? Tools.fromHex('#F83F2D') : Tools.fromHex('#FFFFFF'), fontWeight: FontWeight.w500, fontSize: 12),
              ),
            ],
          ),
        );
      }
    }
    return widgetArr;
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<PreSalesController>(builder: (controller) {
      return Scaffold(
        extendBodyBehindAppBar: true, // 允许 body 从 AppBar 顶部开始布局
        appBar: AppBar(
          backgroundColor: Colors.transparent, // 设置透明
          leading: IconButton(
            icon: const Icon(Icons.arrow_back),
            onPressed: () {
              Navigator.pop(context);
            },
          ),
        ),
        // backgroundColor: Tools.fromHex("#F74133"),
        body: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            //自适应高度的图片
            SizedBox(
              width: double.infinity,
              child: Image.asset("assets/images/presales_bg.png", fit: BoxFit.fitWidth),
            ),

            SizedBox(
              height: 60,
              child: BaseCustomizeSegmentedControl(
                  items: _createItemWidgets(),
                  selectedIndex: controller.selected,
                  onChanged: (index) {
                    controller.change(index);
                  }),
            ),

            //列表
            Expanded(
              child: controller.goodsList.isNotEmpty
                  ? Tools.getPullRefresh(
                      enablePullDown: true,
                      enablePullUp: true,
                      refreshController: controller.baseRefreshCtr,
                      onRefresh: controller.onPageRefresh,
                      onLoading: controller.onPageLoading,
                      child: ListView.builder(
                          padding: EdgeInsets.zero, // 移除默认的内边距
                          itemCount: controller.goodsList.length,
                          itemBuilder: (context, index) {
                            final Map item = controller.goodsList[index];
                            return PreSalesItem(item: item);
                          }))
                  : const NotFound(),
            ),
          ],
        ),
      );
    });
  }
}

///预售实例
class PreSalesItem extends StatelessWidget {
  final Map item;

  const PreSalesItem({
    super.key,
    required this.item,
  });

  @override
  Widget build(BuildContext context) {
    return BaseInteractive(
      onClick: () {
        final id = item['goodsId'];
        Get.to(
          () => GoodsDetailPage(flag: id), // 使用函数懒加载页面实例
          routeName: '${Routes.goodsDetail}?unique=${DateTime.now().millisecondsSinceEpoch}',
          arguments: {"id": id}, // 传递其它参数
          binding: GoodsDetailBinding(flag: id), // 将 tag 参数传递给绑定类
        );
      },
      childWidget: Container(
        padding: EdgeInsets.fromLTRB(18.w, 8.w, 18.w, 8.w),
        decoration: border_radis(Colors.white),
        margin: EdgeInsets.only(bottom: 10.w),
        child: Row(
          children: [
            BaseImage(url: item['mainImage'], width: 116.w, height: 116.h),
            SizedBox(width: 10.w),
            Expanded(
              // 使用 Expanded 确保 Column 占满剩余空间
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Container(
                    padding: EdgeInsets.fromLTRB(8.w, 2.w, 8.w, 2.w),
                    decoration: border_radis(item['balanceAymentEndDataToString'] != null ? Tools.fromHex("#DB4A35") : Colors.white, borderColor: item['balanceAymentEndDataToString'] != null ? Tools.fromHex("#FFED8F") : Colors.white),
                    child: Text(item['balanceAymentEndDataToString'] ?? '', style: setTextStyle(12, FontWeight.w500, Tools.fromHex("#FFFFFF"))),
                  ),
                  SizedBox(height: 20.w),
                  SizedBox(
                    width: 200.w,
                    child: Text(
                      item['commodityName'],
                      style: setTextStyle(14, FontWeight.w500, Tools.fromHex("#333333")),
                      overflow: TextOverflow.ellipsis, // 处理溢出
                      maxLines: 2, // 限制最大行数
                    ),
                  ),
                  SizedBox(height: 20.w),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Row(
                        children: [
                          Text("预售到手价:¥", style: setTextStyle(12, FontWeight.w300, Tools.fromHex("#F83F2D"))),
                          Text(item['specialPrice'].toString(), style: setTextStyle(15, FontWeight.w700, Tools.fromHex("#F83F2D"))),
                        ],
                      ),
                      Container(
                        alignment: Alignment.center,
                        padding: const EdgeInsets.symmetric(horizontal: 8),
                        decoration: BoxDecoration(
                          borderRadius: const BorderRadius.all(Radius.circular(20)),
                          gradient: LinearGradient(
                            colors: [Tools.fromHex("#DC3536"), Tools.fromHex("#FFB4B5")],
                            begin: Alignment.topCenter,
                            end: Alignment.bottomCenter,
                          ),
                        ),
                        height: 23.w,
                        child: Text(
                          "立即预约",
                          style: setTextStyle(12, FontWeight.w300, Tools.fromHex("#FFFFFF")),
                        ),
                      )
                    ],
                  )
                ],
              ),
            )
          ],
        ),
      ),
    );
  }
}
